package com.ajmd.onlineexam.service;

import com.ajmd.onlineexam.entity.FolderPO;
import com.ajmd.onlineexam.entity.QuestionBankPO;
import com.ajmd.onlineexam.entity.TestPaperPO;
import com.ajmd.onlineexam.enumeration.StaticFinalValue;
import com.ajmd.onlineexam.mapper.FolderMapper;
import com.ajmd.onlineexam.mapper.QuestionBankMapper;
import com.ajmd.onlineexam.mapper.TestPaperMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author ajmd
 * @since 2023/3/25 20:50
 */
@Service
public class FolderService {
    @Resource
    private FolderMapper folderMapper;
    @Resource
    private QuestionBankMapper questionBankMapper;
    @Resource
    private TestPaperMapper testPaperMapper;


    @Transactional
    public int addFolder(FolderPO folderPO){
        UUID uuid = UUID.randomUUID();
        folderPO.setId(uuid.toString());
        String fullId = uuid+";";
        if(!folderPO.getParentId().equals("-1")){
            FolderPO parentFolder = folderMapper.selectById(folderPO.getParentId());
            folderPO.setFullId(parentFolder.getFullId()+fullId);
            //更改父目录的子目录数
            parentFolder.setChildNum(parentFolder.getChildNum()+1);
            folderMapper.updateById(parentFolder);
        }else {
            //没有外层文件夹
            folderPO.setFullId(fullId);
        }
        return folderMapper.insert(folderPO);
    }


    public FolderPO findFolderById(String id){
        return folderMapper.selectById(id);
    }

    public List<FolderPO> findFolders(String account,String folderId,Integer folderType,
                                      Integer userType,Integer folderRange){
        QueryWrapper<FolderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FolderPO::getFolderType,folderType)
                .eq(FolderPO::getParentId,folderId);
        //如果是教师还需要做以下限制，否则是管理员不做限制（查看所有）
        if(StaticFinalValue.TEACHER.equals(userType)){
            if(StaticFinalValue.CLICK_ONLY_MY_FOLDERS.equals(folderRange)){
                //仅查看自己创建的
                queryWrapper.lambda().eq(FolderPO::getCreatePerson,account);
            }else {
                //查看公开的和自己创建的
                queryWrapper.lambda().nested(
                    qw->qw.eq(FolderPO::getPublicRange,StaticFinalValue.PUBLIC)
                          .or()
                          .eq(FolderPO::getCreatePerson,account)
                            .eq(FolderPO::getPublicRange,StaticFinalValue.NOT_PUBLIC)
                );
            }
        }
        queryWrapper.lambda().orderByAsc(FolderPO::getSort).orderByDesc(FolderPO::getCreateTime);
        List<FolderPO> folderPOS = folderMapper.selectList(queryWrapper);
        return folderPOS;
    }

    @Transactional
    public int deleteFolder(String folderId){
        //
        FolderPO folderPO = folderMapper.selectById(folderId);
        List<String> idList;//需要修改belongFolderFullId的（题库/试卷）id
        if(folderPO.getFolderType().equals(0)){
            //题库分类
            QueryWrapper<QuestionBankPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(QuestionBankPO::getId);
            queryWrapper.lambda().likeRight(QuestionBankPO::getBelongFolderFullId,folderPO.getFullId());//"__%"
            List<QuestionBankPO> questionBankPOS = questionBankMapper.selectList(queryWrapper);
            idList = questionBankPOS.stream().map(QuestionBankPO::getId).collect(Collectors.toList());
        }else{
            //试题分类
            //查询所属分类路径中包含该分类的所有试卷id
            QueryWrapper<TestPaperPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(TestPaperPO::getId);
            queryWrapper.lambda().likeRight(TestPaperPO::getBelongFolderFullId,folderPO.getFullId());//"__%"
            List<TestPaperPO> testPaperPOS = testPaperMapper.selectList(queryWrapper);
            idList = testPaperPOS.stream().map(TestPaperPO::getId).collect(Collectors.toList());
        }
        // 关联题库或者试卷则不允许删除，todo:后期可改为关联到上级目录
        if(ObjectUtils.isNotEmpty(idList)){
            return -1;
        }
        // 删除当前目录及其子目录
        QueryWrapper<FolderPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().likeLeft(FolderPO::getFullId,folderPO.getFullId());
        folderMapper.delete(queryWrapper);
        //父文件夹的子目录数-1
        if (!folderPO.getParentId().equals("-1")) {
            UpdateWrapper<FolderPO> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(FolderPO::getId, folderPO.getParentId());
            updateWrapper.setSql("child_num = child_num - 1");
            folderMapper.update(null, updateWrapper);
        }
        return folderMapper.deleteById(folderId);
    }

    @Transactional
    public int folderUpdate(FolderPO folderPO){
        UpdateWrapper<FolderPO> updateWrapper = new UpdateWrapper<>();
        //TODO更新时间
//        folderPO.setUpdateTime();
        updateWrapper.lambda().eq(FolderPO::getId,folderPO.getId());
        return folderMapper.update(folderPO,updateWrapper);
    }

    /**
     * 查询当前分类下的子分类是否存在公开分类
     * @param folderId
     * @return
     */
    public Boolean hasPublicChildrenFolder(String folderId){
        LambdaQueryWrapper<FolderPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FolderPO::getPublicRange,StaticFinalValue.PUBLIC)
                .ne(FolderPO::getId,folderId)
                .like(FolderPO::getFullId,folderId);
        return folderMapper.selectList(lambdaQueryWrapper).size()==0?false:true;
    }

    /**
     * 查询当前分类及其子分类是否关联了公开的题库/试卷
     * @param folderId
     * @return
     */
    public Boolean hasAssociationPublic(String folderId,Integer folderType){
        Integer size=0;
        if(StaticFinalValue.QUESTION_BANK_FOLDER.equals(folderType)){
            LambdaQueryWrapper<QuestionBankPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(QuestionBankPO::getPublicRange,StaticFinalValue.PUBLIC)
                    .like(QuestionBankPO::getBelongFolderFullId,folderId);
            size = questionBankMapper.selectList(lambdaQueryWrapper).size();
        }
        if(StaticFinalValue.TEST_PAPER_FOLDER.equals(folderType)){
            LambdaQueryWrapper<TestPaperPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(TestPaperPO::getPublicRange,StaticFinalValue.PUBLIC)
                    .like(TestPaperPO::getBelongFolderFullId,folderId);
            size = testPaperMapper.selectList(lambdaQueryWrapper).size();
        }
        return size==0?false:true;
    }

    /**
     * 返回指定人创建的分类id
     * @param account
     * @return
     */
    public Set<String> getFolderIds(String account){
        LambdaQueryWrapper<FolderPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(FolderPO::getId)
                .eq(FolderPO::getChainCreatedBySamePerson,StaticFinalValue.CHAIN_CREATED_BY_SAME_PERSON)
                .eq(FolderPO::getCreatePerson,account);
        List<FolderPO> folderPOS = folderMapper.selectList(lambdaQueryWrapper);
        Set<String> folderIds=folderPOS.stream().map(FolderPO::getId).collect(Collectors.toSet());
        return folderIds;
    }
}
